package controller

import (
	"IrisStandard/model"
	"IrisStandard/response"
	"IrisStandard/service"
	"IrisStandard/util"
	"github.com/kataras/iris"
	"log"
	"math/rand"
	"regexp"
	"strconv"
)

type AuthController struct {
	Ctx      	iris.Context
	Service     service.UserService
}

func NewAuthController() *AuthController {
	return &AuthController{
		Service: service.NewUserService(),
	}
}

func (c *AuthController) PostLogin() {
	phone := c.Ctx.FormValue("phone")
	password := c.Ctx.FormValue("password")
	user, err := c.Service.GetByPhone(phone)
	if err != nil {
		log.Println(err)
		_, _ = c.Ctx.JSON(response.ServerError)
		return
	}
	if user == nil {
		_, _ = c.Ctx.JSON(response.UserNotExist)
		return
	}
	passwordEncrypt := util.StrToMd5(user.UserId + util.StrToMd5(password))
	if passwordEncrypt != user.Password {
		_, _ = c.Ctx.JSON(response.WrongPassword)
		return
	}
	tokenString := util.GenerateLoginToken(user.UserId, util.LoginTokenExpireMinute)
	_, _ = c .Ctx.JSON(response.SingleObjectResponse{Response: response.Success, Data: tokenString})
}

func (c *AuthController) PostRegisterCaptcha() {
	phone := c.Ctx.FormValue("phone")
	// 检查手机号格式
	phoneRegex, err := regexp.Compile("^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$")
	if err != nil {
		log.Println(err)
		_, _ = c.Ctx.JSON(response.ServerError)
		return
	}
	if !phoneRegex.MatchString(phone) {
		_, _ = c.Ctx.JSON(response.InvalidPhone)
		return
	}
	// 检查手机号是否已被使用
	exist, err := c.Service.CheckExist(phone)
	if err != nil {
		_, _ = c.Ctx.JSON(response.ServerError)
		return
	}
	if exist {
		_, _ = c.Ctx.JSON(response.PhoneHasBeenUsed)
		return
	}
	captcha := strconv.Itoa(rand.Int() + 1000000)[1:7]
	log.Println(captcha)
	//省略发送短信部分
	tokenString := util.GenerateCaptchaToken(phone, captcha, util.CaptchaTokenExpireMinute)
	_, _ = c .Ctx.JSON(response.SingleObjectResponse{Response: response.Success, Data: tokenString})
}

func (c *AuthController) PostRegisterVerify() {
	token := c.Ctx.Request().Header.Get("Authorization")
	tokenPhone, tokenCaptcha, err := util.CheckCaptchaToken(token)
	if err != nil {
		_, _ = c.Ctx.JSON(response.CaptchaExpired)
		return
	}
	phone := c.Ctx.FormValue("phone")
	captcha := c.Ctx.FormValue("captcha")
	password := c.Ctx.FormValue("password")
	// 校验手机号和验证码
	if tokenPhone != phone {
		_, _ = c.Ctx.JSON(response.ReAcquireCaptcha)
		return
	}
	if tokenCaptcha != captcha {
		_, _ = c.Ctx.JSON(response.WrongCaptcha)
		return
	}
	user := model.User{Phone:phone, Password:password}
	add, err := c.Service.Add(user)
	if err != nil {
		_, _ = c.Ctx.JSON(response.ServerError)
		return
	}
	if !add {
		_, _ = c.Ctx.JSON(response.CreateFailed)
		return
	}
	tokenString := util.GenerateLoginToken(user.UserId, util.LoginTokenExpireMinute)
	_, _ = c.Ctx.JSON(response.SingleObjectResponse{Response: response.Success, Data: tokenString})
}